package org.csu.onlineedubackend.task;

import cn.dev33.satoken.stp.StpUtil;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.Map;

@Component
public class HeartbeatTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Scheduled(fixedRate = 60000)
    public void checkStudentHeartbeat() {
        Set<String> keys = redisTemplate.keys("heartbeat:*");
        long now = System.currentTimeMillis();

        if (keys == null || keys.isEmpty()) {
            return; // 没有心跳数据
        }

        for (String key : keys) {
            String lastTimeStr = redisTemplate.opsForValue().get(key);
            if (lastTimeStr == null) {
                continue;
            }

            long lastTime = Long.parseLong(lastTimeStr);
            if (now - lastTime > 60000) { // 超过60秒没心跳
                Integer userId = Integer.parseInt(key.split(":")[1]);

                User user = userService.getById(userId);
                if (user != null && user.getRole() == 1) { // 仅处理学生
                    // 取缓存的IP和User-Agent
                    Map<Object, Object> info = redisTemplate.opsForHash().entries("heartbeat_info:" + userId);
                    String ip = (String) info.getOrDefault("ip", "unknown");
                    String userAgent = (String) info.getOrDefault("userAgent", "unknown");

                    logService.recordLogout(userId, user.getUsername(), ip, userAgent, "学生非正式退出（掉线）");

                    // Sa-Token 踢下线
                    StpUtil.logout(userId);
                }
                // 清理缓存
                redisTemplate.delete(key);
                redisTemplate.delete("heartbeat_info:" + userId);

                System.out.println("自动登出用户：" + userId + "，原因：心跳超时");
            }
        }
    }
}
